package com.eke.serviceimpl;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.eke.bean.Goods;
import com.eke.bean.Users;
import com.eke.dao.GoodsDao;
import com.eke.dao.UsersDao;
import com.eke.service.GoodsService;

@Service
public class GoodsServiceImp implements GoodsService {

	@Resource
	private GoodsDao goodsDao;
	@Resource
	private UsersDao userDao;

	/**
	 * 商品新增
	 * 
	 * @return {@link Boolean}
	 */
	
	public boolean addGoods(Goods goods) {
		if (goods.getId() != null) {
			return goodsDao.addGoods(goods) > 0;
		}
		return false;
	}

	/**
	 * 根据商品id查询商品
	 * 
	 * @return {@link Boolean}
	 */
	
	public Goods queryGoodsById(Integer goods_id) {
		// TODO Auto-generated method stub
		return goodsDao.queryGoodsById(goods_id);
	}

	/**
	 * 根据积分兑换商品
	 * 
	 * @return {@link Boolean}
	 */
	
	public boolean sellGoods(Integer goods_id, Integer users_id) {
		Users users = userDao.queryUserByUserId(users_id);
		Goods goods = goodsDao.queryGoodsById(goods_id);
		if (users.getUserIntegral() >= goods.getGoodsIntegral()) {
			users.setUserIntegral(users.getUserIntegral() - goods.getGoodsIntegral());
			userDao.updateUsersIntegral(users.getUserIntegral(), users_id);
			return true;
		}
		return false;
	}

	/**
	 * 根据商品id删除商品
	 * 
	 * @return {@link Boolean}
	 */
	
	public boolean deleteGoods(Integer goods_id) {
		return goodsDao.deleteGoods(goods_id) > 0;
	}

	/**
	 * 查询商品
	 * 
	 * @param goods_name
	 *            商品名称
	 * @return {@link List}<{@link Goods}> 返回商品集合
	 */
	
	public List<Goods> queryGoods(String goods_name) {
		System.out.println(goods_name);
		List<Goods> list = new ArrayList<Goods>();
		for (int i = 0; i < goods_name.length(); i++) {
			if (Character.isDigit(goods_name.charAt(i))) {
				continue;
			} else {
				return goodsDao.queryGoods(goods_name);
			}
		}
		System.out.println(goods_name);
		Integer goods_id = Integer.parseInt(goods_name);
		list.add(goodsDao.queryGoodsById(goods_id));
		return list;
	}

	/**
	 * 查询所有商品
	 * 
	 * @return {@link List}<{@link Goods}> 返回商品集合
	 */
	
	public List<Goods> queryAllGoods() {
		// TODO Auto-generated method stub
		return goodsDao.queryAllGoods();
	}

	/**
	 * 分页查询商品
	 * 
	 * @param startRow
	 *            开始页
	 * @param pageSize
	 *            数量
	 * @return {@link List}<{@link Goods}> 返回商品集合
	 */
	
	public List<Goods> queryPagingGoods(int startRow, int pageSize) {
		// TODO Auto-generated method stub
		return goodsDao.queryPagingGoods(startRow, pageSize);
	}

}
